package com.hbase;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


/**
 * 初始化配置
 * 
 * @author surh
 * @version 1.0
 * @createtime 2010-4-7上午10:18:21
 * 
 */
public class SystemConfig {
	private final static Logger logger = Logger.getLogger(SystemConfig.class);

	/** 系统所有配置都以key:value的方式存贮在hashmap中 */
	private static final Map<String,String> _configMap = new HashMap<String,String>();

	static{
		try {
			logger.info("loading SystemConfig start ");
			init();
			logger.info("loading SystemConfig sufccess");
			
		} catch (IOException e) {
			logger.error("init config file fail,system exit .... error info : ",e);
			System.exit(-1);
		}
	}

	/**
	 * 执行初始化操作
	 * @throws IOException 
	 * 
	 */
	private static void init() throws IOException {
		/** 设置系统运行的根路径 */
			readProperties("/application.properties");
	}

	public static String getConfig(String key) {
		return getConfig(key, null);
	}
	public static String getConfig(String key, String defaultValue) {
		String value =  _configMap.get(key);
		if (value != null) {
			return value;
		} else {
			return defaultValue;
		}
	}
	public static int getConfig(String key, int defaultValue) {
		String value = _configMap.get(key);
		if (value != null) {
			return Integer.parseInt(value);
		} else {
			return defaultValue;
		}
	}
	/**
	 * 加载配置，并写入到hashmap中
	 * 
	 * @param filePath
	 */
	@SuppressWarnings("unchecked")
	private static void readProperties(String filePath) {
		Properties props = new Properties();
		InputStream inputStream = null;
		try {
//			inputStream = new BufferedInputStream(new FileInputStream(filePath));
			inputStream = SystemConfig.class.getResourceAsStream(filePath);
			props.load(inputStream);
			Enumeration<String> en = (Enumeration<String>)props.propertyNames();
			String key = null;
			while (en.hasMoreElements()) {
				key =  en.nextElement();
				_configMap.put(key, props.getProperty(key));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
